<template>
  <div class="map-location-picker">
    <el-dialog
      title="地图选择位置"
      :visible.sync="visible"
      width="900px"
      append-to-body
      @open="onDialogOpen"
      @close="onDialogClose">

      <div class="picker-header">
        <el-alert
          title="点击地图选择站点位置，您也可以直接在下方输入坐标"
          type="info"
          :closable="false"
          show-icon>
        </el-alert>
      </div>

      <div class="coordinate-inputs">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="GPS纬度：">
              <el-input
                v-model="currentLatitude"
                placeholder="请输入纬度或点击地图选择"
                @change="onCoordinateChange">
                <template slot="append">°</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="GPS经度：">
              <el-input
                v-model="currentLongitude"
                placeholder="请输入经度或点击地图选择"
                @change="onCoordinateChange">
                <template slot="append">°</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="解析地址：">
          <el-input
            v-model="resolvedAddress"
            placeholder="点击地图自动解析地址"
            readonly>
            <template slot="prepend">
              <i class="el-icon-location-information"></i>
            </template>
          </el-input>
        </el-form-item>
      </div>

      <div class="map-container">
        <div id="picker-map-container" class="picker-map-wrapper">
          <div class="map-loading" v-if="mapLoading">
            <i class="el-icon-loading"></i>
            <span>地图加载中...</span>
          </div>
          <div class="map-instructions" v-if="!mapLoading">
            <div class="instruction-tip">
              <i class="el-icon-info"></i>
              点击地图任意位置选择坐标
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button @click="handleClear" v-if="hasCoordinates">
          <i class="el-icon-delete"></i>
          清除坐标
        </el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="!hasCoordinates">
          <i class="el-icon-check"></i>
          确定使用此位置
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MapLocationPicker',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    latitude: {
      type: [String, Number],
      default: ''
    },
    longitude: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      map: null,
      marker: null,
      geocoder: null,
      mapLoading: false,
      currentLatitude: '',
      currentLongitude: '',
      resolvedAddress: ''
    }
  },
  computed: {
    hasCoordinates() {
      return this.currentLatitude && this.currentLongitude &&
        this.currentLatitude != '0' && this.currentLongitude != '0'
    }
  },
  watch: {
    show(val) {
      this.visible = val
      if (!val) {
        this.$emit('update:show', false)
      }
    },
    visible(val) {
      if (!val) {
        this.$emit('update:show', false)
      }
    },
    latitude: {
      handler(val) {
        this.currentLatitude = val || ''
      },
      immediate: true
    },
    longitude: {
      handler(val) {
        this.currentLongitude = val || ''
      },
      immediate: true
    }
  },
  methods: {
    onDialogOpen() {
      this.$nextTick(() => {
        this.initMap()
      })
    },

    onDialogClose() {
      if (this.map) {
        this.map.destroy()
        this.map = null
        this.marker = null
        this.geocoder = null
      }
    },

    async initMap() {
      this.mapLoading = true

      try {
        // 动态加载高德地图API
        if (!window.AMap) {
          await this.loadAmapScript()
        }

        // 设置地图中心点
        let center = [116.397428, 39.90923] // 默认北京
        if (this.hasCoordinates) {
          center = [parseFloat(this.currentLongitude), parseFloat(this.currentLatitude)]
        }

        // 创建地图实例
        this.map = new window.AMap.Map('picker-map-container', {
          zoom: 13,
          center: center,
          mapStyle: 'amap://styles/normal'
        })

        // 创建地理编码器
        this.geocoder = new window.AMap.Geocoder()

        // 如果已有坐标，添加标记
        if (this.hasCoordinates) {
          this.addMarker(center)
          this.getAddress(center)
        }

        // 绑定地图点击事件
        this.map.on('click', (e) => {
          const lng = e.lnglat.getLng()
          const lat = e.lnglat.getLat()

          this.currentLatitude = lat.toFixed(6)
          this.currentLongitude = lng.toFixed(6)

          this.addMarker([lng, lat])
          this.getAddress([lng, lat])
        })

      } catch (error) {
        console.error('地图初始化失败:', error)
        this.$message.error('地图加载失败，请检查网络连接')
      } finally {
        this.mapLoading = false
      }
    },

    loadAmapScript() {
      return new Promise((resolve, reject) => {
        if (window.AMap) {
          resolve()
          return
        }

        const script = document.createElement('script')
        script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=您的高德地图API密钥&plugin=AMap.Geocoder'
        script.onload = resolve
        script.onerror = reject
        document.head.appendChild(script)
      })
    },

    addMarker(position) {
      // 移除现有标记
      if (this.marker) {
        this.map.remove(this.marker)
      }

      // 添加新标记
      this.marker = new window.AMap.Marker({
        position: position,
        icon: new window.AMap.Icon({
          size: new window.AMap.Size(32, 32),
          image: 'data:image/svg+xml;base64,' + btoa(`
            <svg width="32" height="32" xmlns="http://www.w3.org/2000/svg">
              <circle cx="16" cy="26" r="3" fill="#409EFF" opacity="0.3"/>
              <circle cx="16" cy="12" r="8" fill="#67C23A" stroke="#fff" stroke-width="2"/>
              <circle cx="16" cy="12" r="3" fill="#fff"/>
              <line x1="16" y1="20" x2="16" y2="24" stroke="#409EFF" stroke-width="2"/>
            </svg>
          `),
          imageSize: new window.AMap.Size(32, 32)
        })
      })

      this.map.add(this.marker)
      this.map.setCenter(position)
    },

    getAddress(position) {
      if (this.geocoder) {
        this.geocoder.getAddress(position, (status, result) => {
          if (status === 'complete' && result.regeocode) {
            this.resolvedAddress = result.regeocode.formattedAddress
          } else {
            this.resolvedAddress = '地址解析失败'
          }
        })
      }
    },

    onCoordinateChange() {
      if (this.hasCoordinates && this.map) {
        const lat = parseFloat(this.currentLatitude)
        const lng = parseFloat(this.currentLongitude)

        if (!isNaN(lat) && !isNaN(lng)) {
          const position = [lng, lat]
          this.addMarker(position)
          this.getAddress(position)
        }
      }
    },

    handleConfirm() {
      if (this.hasCoordinates) {
        this.$emit('confirm', {
          latitude: this.currentLatitude,
          longitude: this.currentLongitude,
          address: this.resolvedAddress
        })
        this.visible = false
      } else {
        this.$message.warning('请先选择位置')
      }
    },

    handleCancel() {
      this.visible = false
    },

    handleClear() {
      this.currentLatitude = ''
      this.currentLongitude = ''
      this.resolvedAddress = ''
      if (this.marker) {
        this.map.remove(this.marker)
        this.marker = null
      }
    }
  }
}
</script>

<style scoped>
.picker-header {
  margin-bottom: 20px;
}

.coordinate-inputs {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.coordinate-inputs .el-form-item {
  margin-bottom: 15px;
}

.coordinate-inputs .el-form-item:last-child {
  margin-bottom: 0;
}

.map-container {
  position: relative;
  height: 400px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.picker-map-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #606266;
  z-index: 10;
}

.map-loading i {
  font-size: 24px;
  margin-bottom: 8px;
}

.map-instructions {
  position: absolute;
  top: 15px;
  left: 15px;
  z-index: 10;
}

.instruction-tip {
  background: rgba(64, 158, 255, 0.9);
  color: white;
  padding: 8px 15px;
  border-radius: 4px;
  font-size: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.instruction-tip i {
  margin-right: 5px;
}

/* 高德地图样式覆盖 */
::v-deep .amap-copyright {
  display: none !important;
}

::v-deep .amap-logo {
  display: none !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .coordinate-inputs {
    padding: 10px;
  }

  .map-container {
    height: 300px;
  }
}
</style>